﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Deepseek_Robot
{
    public class TyModel : TyClientBase
    {
        private string _apiKey;
        private string _apiUrl;
        private string _endpointId;
        private static readonly HttpClient client = new HttpClient();

        public TyModel(string configjson) : base(configjson)
        {
            // 解析configjson
            var config = JsonConvert.DeserializeObject<dynamic>(configjson);
            _apiKey = config.ApiKey;
            _apiUrl = config.Url;
            _endpointId = config.EndpointId;
        }

        public override async IAsyncEnumerable<string> ChatAIAsync(string input)
        {
           
            var requestBody = new
            {
                model = _endpointId,
                messages = new[]
                {
                new { role = "system", content = "你是一个RobotStudio RAPID编程高手，精通RAPID编程语言,我提给你的问题只要返回RAPID的纯代码和注释就可以。直接输出mod内容" },
                new { role = "user", content = input }
            },
                stream = true
            };

            var json = JsonConvert.SerializeObject(requestBody);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(_apiUrl),
                Content = content
            };

            request.Headers.Add("Authorization", $"Bearer {_apiKey}");

            var response = client.Send(request, HttpCompletionOption.ResponseHeadersRead);

            var fullResponse = new StringBuilder();

            using (var stream = response.Content.ReadAsStream())
            using (var reader = new System.IO.StreamReader(stream))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (line.StartsWith("data:"))
                    {
                        var jsonString = line.Substring(5).Trim();
                        if (jsonString == "[DONE]")
                        {
                            break;
                        }
                        var jsonObj = JObject.Parse(jsonString);
                        var contentDelta = jsonObj["choices"]?[0]?["delta"]?["content"]?.ToString();
                        if (contentDelta != null)
                        {
                            yield return contentDelta;
                        }
                    }
                }
            }
    }
       
    }
}
